//
//  TicketPopView.m
//  TQY
//
//  Created by 甘世清 on 2024/11/9.
//

#import "TicketPopView.h"
#import "TicketCollectionViewCell.h"
#import <RMStore/RMStore.h>
#import "MessageTopView.h"
@implementation TicketPopView

+ (void)SQ_showTickView:(UIView *)view{
    if ([UserModel share].isTicket) {//如果已购买
        return;
    }
    if ([UserModel share].gender  == 2) {//如果是女性
        return;
    }
    if ([[UserModel share].userid isEqualToString:@"11"]) {//如果是测试号
        return;
    }
    NSString * ticket_switch = [Manager SQ_stringForKey:@"ticket_switch"];
    if ([ticket_switch isEqualToString:@"0"]) {//如果后台没开
        return;
    }
    TicketPopView * vc = [[TicketPopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                           parentView:view
                                             popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleBottom;
    pop.isAvoidKeyboard = NO;
    [pop pop];
    LSTPopViewWK(pop)
    [ pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
   
    [vc setTicketBlock:^{
        [wk_pop dismiss];
    }];
}
- (void)SQ_UIViewForSelfView{
    self.backgroundColor = UIColor.whiteColor;
    UIImageView * bgImageView = [[UIImageView alloc]init];
    bgImageView.image = SQGetImage(@"登陆页");
    [self addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self);
        make.height.mas_equalTo(TopHeight+100);
    }];
    [self.cwcarousel.carouselView registerClass:[TicketCollectionViewCell class] forCellWithReuseIdentifier:@"TicketCollectionViewCell"];
    [self addSubview:self.cwcarousel];
    
    [self addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
        make.bottom.equalTo(self.mas_bottom);
            make.width.mas_equalTo(SCREEN_WIDETH);
            make.height.mas_equalTo(380);
    }];
    
    NSString * app_recommended = [Manager SQ_stringForKey:@"app_recommended"];
    if ([app_recommended isEqualToString:@"1"]) {
        [self addSubview:self.footViews];
        [self.footViews mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.bottom.equalTo(self.bottomView.mas_top);
            make.height.mas_equalTo(70);
        }];
    }
    
    [self SQ_header];
    [self SQ_getConfig];
}

-(void)SQ_header{
    [HttpTool post:@"ticket/list" paramDic:[NSMutableDictionary new] successBlock:^(BaseModel * _Nonnull httpModel) {
        NSArray * array = [[NSArray alloc]initWithArray:httpModel.data];
    [self.jsonArray removeAllObjects];
    [self.jsonArray addObjectsFromArray:array];
    [self.cwcarousel freshCarousel];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
}
-(void)SQ_getConfig{
    WS(weakSelf);
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"ticket_switch,good_comment_switch" forKey:@"keys"];
    [HttpTool post:@"config/list" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        NSArray * array = [[NSArray alloc]initWithArray:httpModel.data];
        for (NSDictionary * switchDic in array) {
            NSString * key = [NSString stringWithFormat:@"%@",[switchDic objectForKey:@"key"]];
            if ([key isEqualToString:@"good_comment_switch"]) {
                NSString * value = [NSString stringWithFormat:@"%@",[switchDic objectForKey:@"value"]];
                [Manager SQ_SetObject:value FormKey:@"good_comment_switch"];
                if ([value isEqualToString:@"1"]) {
                    weakSelf.bottomView.fiveBtn.hidden = NO;
                } else {
                    weakSelf.bottomView.fiveBtn.hidden = YES;
                }
            } else if ([key isEqualToString:@"ticket_switch"]) {
                NSString * value = [NSString stringWithFormat:@"%@",[switchDic objectForKey:@"value"]];
                [Manager SQ_SetObject:value FormKey:@"ticket_switch"];
                if (![value isEqualToString:@"1"]) {
                    self.TicketBlock();
                }
            }
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
    }];
}

- (void)CWCarousel:(CWCarousel *)carousel didSelectedAtIndex:(NSInteger)index{

}
- (NSInteger)numbersForCarousel{
    return self.jsonArray.count;
}
- (UICollectionViewCell *)viewForCarousel:(CWCarousel *)carousel indexPath:(NSIndexPath *)indexPath index:(NSInteger)index{

    TicketCollectionViewCell *cell = [carousel.carouselView dequeueReusableCellWithReuseIdentifier:@"TicketCollectionViewCell" forIndexPath:indexPath];
    NSDictionary * dic = [self.jsonArray objectAtIndex:index];
    NSString * header = [NSString stringWithFormat:@"%@",[dic objectForKey:@"img"]];
    [cell.bgImage sd_setImageWithURL:SQURLImage(header) placeholderImage:SQGetImage(@"zanwutouxiang")];
    cell.juliLabel.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"distance"]];
    cell.nameLabel.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]];
    return cell;
}

-(void)SQ_PayMenpiao{
    //调用内购
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSString * appleId = [NSString stringWithFormat:@"%@",[self.bottomView.ticketDic objectForKey:@"appleId"]];
    WS(weakSelf);
     [[RMStore defaultStore] addPayment:appleId success:^(SKPaymentTransaction *transaction) {
            [weakSelf checkIAPResultWithtransactionReceiptblock];
        } failure:^(SKPaymentTransaction *transaction, NSError *error) {
            [YJProgressHUD showMsgWithoutView: SQNSLocalString(@"交易失败")];
    }];
}
- (void)checkIAPResultWithtransactionReceiptblock
{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        if (receiptURL) {
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
         
            NSString *encodeStr = [receiptData base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithLineFeed];
             NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:encodeStr forKey:@"certificate"];
             [YJProgressHUD SQ_showMsgWithoutView:@""];
            [HttpTool post:@"ticket/pay" paramDic:dic successBlock:^(BaseModel * _Nullable httpModel) {
                [UserModel share].isTicket = YES;
                [UserModel updateLocalUserModel:[UserModel share]];
                [YJProgressHUD showMsgWithoutView:@"购买成功"];
                for (SKPaymentTransaction *aTransaction in [[SKPaymentQueue defaultQueue] transactions]) {
                    [[SKPaymentQueue defaultQueue]finishTransaction:aTransaction];
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (self.TicketBlock) {
                        self.TicketBlock();
                    }
                });
            } andFailBloc:^(BaseModel * _Nullable httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
        }else{
            [YJProgressHUD hide];
        }
}
- (void)dealloc{
//    [self.bottomView removeFromSuperview];
    DTLog(@"是否释放了-------");
}

-(NSMutableArray*)jsonArray
{
    if (!_jsonArray) {
        _jsonArray = [[NSMutableArray alloc]init];
    }
    return _jsonArray;
}

- (CWCarousel *)cwcarousel{
    if (!_cwcarousel) {
        CWFlowLayout * laye = [[CWFlowLayout alloc]initWithStyle:CWCarouselStyle_H_2];
        laye.itemWidth = SCREEN_WIDETH - 40;
//        laye.itemSpace_H = -10;
        _cwcarousel = [[CWCarousel alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDETH, SCREEN_HEIGHT-FootHeight-44-30) delegate:self datasource:self flowLayout:laye];
        _cwcarousel.isAuto = YES;
        _cwcarousel.pageControl.hidden = YES;
        _cwcarousel.autoTimInterval = 1.5;
        _cwcarousel.userInteractionEnabled = NO;
        _cwcarousel.backgroundColor = UIColor.clearColor;
    }
    return _cwcarousel;
}
- (ticketDetailsView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[ticketDetailsView alloc]init];
        [_bottomView.addbtn.btn addTarget:self action:@selector(SQ_PayMenpiao) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomView;
}

- (RecommendedView *)footViews{
    if (!_footViews) {
        _footViews = [[RecommendedView alloc]init];
    }
    return _footViews;
}
@end
